var localZq = document.getElementById('zqLocalName');

var controls = document.getElementById('zq');

var centerCity = document.getElementById('centerCity');

var province = document.getElementById("sel-city-btnl");
var city = document.getElementById("sel-city-btnr");

var proList = document.getElementById("proList");
var cityList = document.getElementById("cityList");
var datas;

// 当前城市地址
var zqLocalName = '加载中';

// 省数据
var shengDatas = [
    { name: 'A', list: [] },
    { name: 'B', list: [] },
    { name: 'C', list: [] },
    { name: 'D', list: [] },
    { name: 'E', list: [] },
    { name: 'F', list: [] },
    { name: 'G', list: [] },
    { name: 'H', list: [] },
    { name: 'I', list: [] },
    { name: 'J', list: [] },
    { name: 'K', list: [] },
    { name: 'L', list: [] },
    { name: 'M', list: [] },
    { name: 'N', list: [] },
    { name: 'O', list: [] },
    { name: 'P', list: [] },
    { name: 'Q', list: [] },
    { name: 'R', list: [] },
    { name: 'S', list: [] },
    { name: 'T', list: [] },
    { name: 'U', list: [] },
    { name: 'V', list: [] },
    { name: 'W', list: [] },
    { name: 'X', list: [] },
    { name: 'Y', list: [] },
    { name: 'Z', list: [] }
];

// 市数据
var shiDatas = [
    { name: 'A', list: [] },
    { name: 'B', list: [] },
    { name: 'C', list: [] },
    { name: 'D', list: [] },
    { name: 'E', list: [] },
    { name: 'F', list: [] },
    { name: 'G', list: [] },
    { name: 'H', list: [] },
    { name: 'I', list: [] },
    { name: 'J', list: [] },
    { name: 'K', list: [] },
    { name: 'L', list: [] },
    { name: 'M', list: [] },
    { name: 'N', list: [] },
    { name: 'O', list: [] },
    { name: 'P', list: [] },
    { name: 'Q', list: [] },
    { name: 'R', list: [] },
    { name: 'S', list: [] },
    { name: 'T', list: [] },
    { name: 'U', list: [] },
    { name: 'V', list: [] },
    { name: 'W', list: [] },
    { name: 'X', list: [] },
    { name: 'Y', list: [] },
    { name: 'Z', list: [] }
];

// 省会城市数据
centerData = []


function init() {
    localZq.innerHTML = zqLocalName;

    // 初始化省市数据
    setData();

    controls.addEventListener('click', controlsClick);

    province.addEventListener("click", proSelectClick);

    city.addEventListener("click", citySelectClick);
}



function hasClass(elem, cls) {
    cls = cls || '';
    if (cls.replace(/\s/g, '').length === 0) {
        return false;
    }
    return new RegExp(' ' + cls + ' ').test(' ' + elem.className + ' ');
}

function addClass(elem, cls) {
    if (!hasClass(elem, cls)) {
        elem.className = elem.className === '' ? cls : elem.className + ' ' + cls;
    }
}

function removeClass(elem, cls) {
    if (hasClass(elem, cls)) {
        var newClass = ' ' + elem.className.replace(/[\t\r\n]/g, '') + ' ';
        while (newClass.indexOf(' ' + cls + ' ') >= 0) {
            newClass = newClass.replace(' ' + cls + ' ', ' ');
        }
        elem.className = newClass.replace(/^\s+|\s+$/g, '');
    }
}

function showById(id) {
    document.getElementById(id).style.display = 'block';
}

function hideById(id) {
    document.getElementById(id).style.display = 'none';
}



function controlsClick() {
    if (!hasClass(controls, 'active')) {
        addClass(controls, 'active');
        showById('popup_main');
        proSelectClick();
        showCenterCity();
    } else {
        removeClass(controls, 'active');
        hideById('popup_main');
    }
}

function showCenterCity() {

    if (!centerData || centerData.length == 0) {
        addClass(document.getElementById("centerCityItem"), 'display')
    } else {
        centerCity.innerHTML = "";
        addClass(document.getElementById("centerCityItem"), 'block')

        centerData.forEach(function (data) {
            var a = document.createElement("a");
            a.setAttribute("class", "city-link");
            a.innerHTML = data.cname;
            a.addEventListener("click", function () {
                amap.zoomToPoint(data.lon, data.lat, data.code == 000000 ? 3 : 11);
            })
            centerCity.appendChild(a);
        })
    }
}

function proSelectClick() {

    addClass(province, 'sel-city-btnl-sel');

    if (hasClass(city, 'sel-city-btnl-sel')) {
        removeClass(city, 'sel-city-btnl-sel');
    }

    cityList.setAttribute("class", "display");
    proList.setAttribute("class", "block");

    proList.innerHTML = "";

    //遍历所有省
    shengDatas.forEach(function (shenData) {
        var div1 = document.createElement("div")


        // 遍历一某字母开头的省
        shenData.list.forEach(function (list, i) {
            var tr1 = document.createElement("tr")

            // 渲染字母
            var td1 = document.createElement("td");
            td1.setAttribute("class", "sel-city-td-letter");
            if (i == 0) {
                var div2 = document.createElement("div");
                div2.innerText = shenData.name;
                td1.appendChild(div2);
                td1.setAttribute("id", shenData.name);
            }
            tr1.appendChild(td1);

            // 渲染省名
            var td2 = document.createElement("td");
            td2.setAttribute("class", "sel-city-td-sf");
            var a1 = document.createElement("a");
            a1.innerText = list.cname;
            a1.addEventListener('click', function () {
                amap.zoomToPoint(list.lon, list.lat, 6);
            })
            td2.appendChild(a1);
            tr1.appendChild(td2)

            // 渲染省包含的市
            var td3 = document.createElement("td");
            td3.setAttribute("class", "sel-city-td-item");
            list.list.forEach(function (city) {
                var a2 = document.createElement("a");
                a2.innerText = city.cname;
                a2.addEventListener('click', function () {
                    amap.zoomToPoint(city.lon, city.lat, 11);
                })
                td3.appendChild(a2);
            })

            tr1.appendChild(td3)

            div1.appendChild(tr1);

        });

        // 如果有以该字母开头的省则留下空格
        if (shenData.list.length > 0) {
            var tr2 = document.createElement("tr")
            var td4 = document.createElement("td");
            td4.setAttribute("colspan", 3);
            var div3 = document.createElement("div");
            div3.innerText = shenData.name;
            div3.setAttribute("class", "sel-city-tr-splitline");
            td4.appendChild(div3);
            tr2.appendChild(td4)
            div1.appendChild(tr2);
        }

        proList.appendChild(div1);

    });

}

function citySelectClick() {
    addClass(city, 'sel-city-btnl-sel');

    if (hasClass(province, 'sel-city-btnl-sel')) {
        removeClass(province, 'sel-city-btnl-sel');
    }

    cityList.innerHTML = "";

    cityList.setAttribute("class", "block");
    proList.setAttribute("class", "display");

    //遍历所有市
    shiDatas.forEach(function (shiData) {
        var div1 = document.createElement("div")

        if (shiData.list.length > 0) {
            var tr1 = document.createElement("tr")

            // 渲染市首字母
            var td1 = document.createElement("td");
            td1.setAttribute("class", "sel-city-td-letter");
            var div2 = document.createElement("div");
            div2.innerText = shiData.name;
            td1.appendChild(div2);
            tr1.appendChild(td1);


            // 渲染以该字母开头的城市
            var td2 = document.createElement("td");
            shiData.list.forEach(function (list) {
                var a1 = document.createElement("a");
                a1.innerText = list.cname;
                a1.addEventListener('click', function () {
                    amap.zoomToPoint(list.lon, list.lat, 11);
                })
                td2.appendChild(a1);
            })
            tr1.appendChild(td2);

            div1.appendChild(tr1);


            // 如果有以该字母开头的省则留下空格
            var tr2 = document.createElement("tr")
            var td3 = document.createElement("td");
            td3.setAttribute("colspan", 2);
            var div3 = document.createElement("div");
            div3.innerText = shiData.name;
            div3.setAttribute("class", "sel-city-tr-splitline");
            td3.appendChild(div3);
            tr2.appendChild(td3)
            div1.appendChild(tr2);
        }


        cityList.appendChild(div1);

    });
}

function setData() {
    var ajax = new XMLHttpRequest();
    ajax.overrideMimeType("application/json");
    ajax.open("GET", "../data/china_admin_city.json", true);
    ajax.onreadystatechange = function () {
        if (ajax.readyState === 4 && ajax.status == "200") {
            var allData = JSON.parse(ajax.responseText);
            if (allData) {
                console.log(allData);
                datas = allData.data;
                shengOption();
                shiOption();
                centerOption();
            }
        }
    };
    ajax.send(null);
}

function shengOption() {
    datas.forEach(function (data) {
        // 数据首字母
        var fb = data.pyname.substr(0, 1);
        shengDatas.forEach(function (s) {
            if (s.name === fb) {
                s.list.push(data);
            }
        });
    });
}

function shiOption() {
    datas.forEach(function (data) {
        data.list.forEach(function (city) {
            // 数据首字母
            var fb = city.pyname.substr(0, 1);
            shiDatas.forEach(function (s) {
                if (s.name === fb) {
                    s.list.push(city);
                }
            });
        });
    });
}

function centerOption() {
    if (datas[0] && datas[0].list && datas[0].list.length > 0) {
        centerData = datas[0].list;
    }
}


// 逆地理编码
function reverseGeoCodeSearch() {
    const level = amap.getZoom();
    const center = amap.getCenter();
    map.Factory.GeocodeData(function (geocodeData) {
        // 地理编码查询
        geocodeData.reverseGeoCodeSearch('mine', {
            location: center[0] + "," + center[1]
        }, function (res) {
            if (res.code == "0") {
                if (!res.data) {
                    return;
                }
                if (level > 7) {
                    if (res.data.city == '直辖县级行政单位') {//海南特殊处理
                        zqLocalName = res.data.country;
                    } else {
                        if (res.data.city) {
                            zqLocalName = res.data.city;
                        } else {
                            zqLocalName = "全国";
                        }
                    }
                } else if (level > 3) {
                    zqLocalName = res.data.province;
                } else {
                    zqLocalName = "全国";
                }
            } else {
                zqLocalName = "全国";
            }
            localZq.innerHTML = zqLocalName;
        }, function () {
            console.log("逆定理编码服务不可用")
            localZq.innerHTML = "全国";
        });
    });
}